home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 August: Tool Chest / Dev.CD Aug 00 TC Disk 2.toast / pc / sample code / overview / sample (traffic light) / sampleinit.c < prev   
Encoding:
C/C++ Source or Header  |  2000-06-23  |  12.2 KB  |  288 lines

  1. /*
  2.     File:        SampleInit.c
  3.  
  4.     Contains:    Sample is an example application that demonstrates how to
  5.                 initialize the commonly used toolbox managers, operate 
  6.                 successfully under MultiFinder, handle desk accessories, 
  7.                 and create, grow, and zoom windows.
  8.     
  9.                 It does not by any means demonstrate all the techniques 
  10.                 you need for a large application. In particular, Sample 
  11.                 does not cover exception handling, multiple windows/documents, 
  12.                 sophisticated memory management, printing, or undo. All of 
  13.                 these are vital parts of a normal full-sized application.
  14.     
  15.                 This application is an example of the form of a Macintosh 
  16.                 application; it is NOT a template. It is NOT intended to be 
  17.                 used as a foundation for the next world-class, best-selling, 
  18.                 600K application. A stick figure drawing of the human body may 
  19.                 be a good example of the form for a painting, but that does not 
  20.                 mean it should be used as the basis for the next Mona Lisa.
  21.     
  22.                 We recommend that you review this program or TESample before 
  23.                 beginning a new application.
  24.     Written by:     
  25.  
  26.     Copyright:    Copyright © 1989-1999 by Apple Computer, Inc., All Rights Reserved.
  27.  
  28.                 You may incorporate this Apple sample source code into your program(s) without
  29.                 restriction. This Apple sample source code has been provided "AS IS" and the
  30.                 responsibility for its operation is yours. You are not permitted to redistribute
  31.                 this Apple sample source code as "Apple sample source code" after having made
  32.                 changes. If you're going to re-distribute the source, we require that you make
  33.                 it clear in the source that the code was descended from Apple sample source
  34.                 code, but that you've made changes.
  35.  
  36.     Change History (most recent first):
  37.                 8/13/1999    Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
  38.                 
  39.  
  40. */
  41.  
  42. /* Segmentation strategy:
  43.  
  44.    This program consists of three segments.
  45.    1. "Main" contains most of the code, including the MPW libraries, and the
  46.       main program.  This segment is in the file Sample.c
  47.    2. "Initialize" contains code that is only used once, during startup, and
  48.       can be unloaded after the program starts.  This segment is in the file
  49.       SampleInit.c.
  50.    3. "%A5Init" is automatically created by the Linker to initialize globals
  51.       for the MPW libraries and is unloaded right away. */
  52.  
  53.  
  54. /* SetPort strategy:
  55.  
  56.    Toolbox routines do not change the current port. In spite of this, in this
  57.    program we use a strategy of calling SetPort whenever we want to draw or
  58.    make calls which depend on the current port. This makes us less vulnerable
  59.    to bugs in other software which might alter the current port (such as the
  60.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  61.    Hopefully, this also makes the routines from this program more self-contained,
  62.    since they don't depend on the current port setting. */
  63.  
  64.  
  65. #pragma segment Initialize
  66.  
  67. #include <Limits.h>
  68. #include <Types.h>
  69. #include <Resources.h>
  70. #include <QuickDraw.h>
  71. #include <Fonts.h>
  72. #include <Events.h>
  73. #include <Windows.h>
  74. #include <Menus.h>
  75. #include <TextEdit.h>
  76. #include <Dialogs.h>
  77. #include <Desk.h>
  78. #include <ToolUtils.h>
  79. #include <Memory.h>
  80. #include <SegLoad.h>
  81. #include <Files.h>
  82. #include <OSUtils.h>
  83. #include <DiskInit.h>
  84. #include <Packages.h>
  85. #include <Traps.h>
  86. #include <OSUtils.h>
  87. #include "Sample.h"        /* bring in all the #defines for Sample */
  88.  
  89.  
  90. /* The "g" prefix is used to emphasize that a variable is global. */
  91. /* All are extern since the variables are declared in the main segment. */
  92.  
  93. /* GMac is used to hold the result of a SysEnvirons call. This makes
  94.    it convenient for any routine to check the environment. */
  95. extern SysEnvRec    gMac;                /* set up by Initialize */
  96.  
  97. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  98.    trap is available. If it is false, we know that we must call GetNextEvent. */
  99. extern Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  100.  
  101. /* GInBackground is maintained by our osEvent handling routines. Any part of
  102.    the program can check it to find out if it is currently in the background. */
  103. extern Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  104.  
  105.  
  106. /* The following globals are the state of the window. If we supported more than
  107.    one window, they would be attatched to each document, rather than globals. */
  108.  
  109. /* GStopped tells whether the stop light is currently on stop or go. */
  110. extern Boolean        gStopped;            /* maintained by Initialize and SetLight */
  111.  
  112. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  113. extern Rect        gStopRect;            /* set up by Initialize */
  114. extern Rect        gGoRect;            /* set up by Initialize */
  115.  
  116.  
  117. /*    Set up the whole world, including global variables, Toolbox managers,
  118.     and menus. We also create our one application window at this time.
  119.     Since window storage is non-relocateable, how and when to allocate space
  120.     for windows is very important so that heap fragmentation does not occur.
  121.     Because Sample has only one window and it is only disposed when the application
  122.     quits, we will allocate its space here, before anything that might be a locked
  123.     relocatable object gets into the heap. This way, we can force the storage to be
  124.     in the lowest memory available in the heap. Window storage can differ widely
  125.     amongst applications depending on how many windows are created and disposed. */
  126.  
  127. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  128.     this module. If an error is detected, instead of merely doing an ExitToShell,
  129.     which leaves the user without much to go on, we call AlertUser, which puts
  130.     up a simple alert that just says an error occurred and then calls ExitToShell.
  131.     Since there is no other cleanup needed at this point if an error is detected,
  132.     this form of error- handling is acceptable. If more sophisticated error recovery
  133.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  134.  
  135. void Initialize()
  136. {
  137.     Handle        menuBar;
  138.     WindowPtr    window;
  139.     long        total, contig;
  140.     EventRecord event;
  141.     short        count;
  142.  
  143.     gInBackground = false;
  144.  
  145.     InitGraf((Ptr) &qd.thePort);
  146.     InitFonts();
  147.     InitWindows();
  148.     InitMenus();
  149.     TEInit();
  150.     InitDialogs(nil);
  151.     InitCursor();
  152.     
  153.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  154.          if you are using it. */
  155.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  156.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  157.         of checking for port availability themselves. */
  158.     
  159.     /*    This next bit of code is necessary to allow the default button of our
  160.         alert be outlined.
  161.         1.02 - Changed to call EventAvail so that we don't lose some important
  162.         events. */
  163.      
  164.     for (count = 1; count <= 3; count++)
  165.         EventAvail(everyEvent, &event);
  166.     
  167.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  168.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  169.         call to SysEnvirons by calling it after initializing AppleTalk. */
  170.      
  171.     SysEnvirons(kSysEnvironsVersion, &gMac);
  172.     
  173.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  174.     
  175.     if (gMac.machineType < 0) AlertUser();
  176.     
  177.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  178.         in TrapAvailable if a tool trap value is out of range. */
  179.         
  180.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  181.  
  182.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  183.         ApplicationZone, and StackSpace and comparing that to the minimum size we told
  184.         MultiFinder we needed. This did not work well because it assumed too much about
  185.         the relationship between what we asked MultiFinder for and what we would actually
  186.         get back, as well as how to measure it. Instead, we will use an alternate
  187.         method comprised of two steps. */
  188.      
  189.     /*    It is better to first check the size of the application heap against a value
  190.         that you have determined is the smallest heap the application can reasonably
  191.         work in. This number should be derived by examining the size of the heap that
  192.         is actually provided by MultiFinder when the minimum size requested is used.
  193.         The derivation of the minimum size requested from MultiFinder is described
  194.         in Sample.h. The check should be made because the preferred size can end up
  195.         being set smaller than the minimum size by the user. This extra check acts to
  196.         insure that your application is starting from a solid memory foundation. */
  197.      
  198.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  199.     
  200.     /*    Next, make sure that enough memory is free for your application to run. It
  201.         is possible for a situation to arise where the heap may have been of required
  202.         size, but a large scrap was loaded which left too little memory. To check for
  203.         this, call PurgeSpace and compare the result with a value that you have determined
  204.         is the minimum amount of free memory your application needs at initialization.
  205.         This number can be derived several different ways. One way that is fairly
  206.         straightforward is to run the application in the minimum size configuration
  207.         as described previously. Call PurgeSpace at initialization and examine the value
  208.         returned. However, you should make sure that this result is not being modified
  209.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  210.         PurgeSpace. Make sure to remove that call before shipping, though. */
  211.     
  212.     /* ZeroScrap(); */
  213.  
  214.     PurgeSpace(&total, &contig);
  215.     if (total < kMinSpace) AlertUser();
  216.  
  217.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  218.         to check memory is that we can now give the user an alert to tell him/her what
  219.         happened. Although it is possible that the memory situation could be worsened by
  220.         displaying an alert, MultiFinder would gracefully exit the application with
  221.         an informative alert if memory became critical. Here we are acting more
  222.         in a preventative manner to avoid future disaster from low-memory problems. */
  223.  
  224.     /*     we will allocate our own window storage instead of letting the Window
  225.         Manager do it because GetNewWindow may load in temp. resources before
  226.         making the NewPtr call, and this can lead to heap fragmentation. */
  227.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  228.     if ( window == nil ) AlertUser();
  229.     window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  230.  
  231.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  232.     if ( menuBar == nil ) AlertUser();
  233.     SetMenuBar(menuBar);                    /* install menus */
  234.     DisposeHandle(menuBar);
  235.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  236.     DrawMenuBar();
  237.     
  238.     gStopped = true;
  239.     if ( !GoGetRect(rStopRect, &gStopRect) )
  240.         AlertUser();                        /* the stop light rectangle */
  241.     if ( !GoGetRect(rGoRect, &gGoRect) )
  242.         AlertUser();                        /* the go light rectangle */
  243. } /*Initialize*/
  244.  
  245.  
  246. /*    This utility loads the global rectangles that are used by the window
  247.     drawing routines. It shows how the resource manager can be used to hold
  248.     values in a convenient manner. These values are then easily altered without
  249.     having to re-compile the source code. In this particular case, we know
  250.     that this routine is being called at initialization time. Therefore,
  251.     if a failure occurs here, we will assume that the application is in such
  252.     bad shape that we should just exit. Your error handling may differ, but
  253.     the check should still be made. */
  254.     
  255. Boolean GoGetRect(short rectID, Rect *theRect)
  256. {
  257.     Handle        resource;
  258.     
  259.     resource = GetResource('RECT', rectID);
  260.     if ( resource != nil ) {
  261.         *theRect = **((Rect**) resource);
  262.         return true;
  263.     }
  264.     else
  265.         return false;
  266. } /* GoGetRect */
  267.  
  268.  
  269. /*    Check to see if a given trap is implemented. This is only used by the
  270.     Initialize routine in this program, so we put it in the Initialize segment.
  271.     The recommended approach to see if a trap is implemented is to see if
  272.     the address of the trap routine is the same as the address of the
  273.     Unimplemented trap. */
  274. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  275.     if a ToolTrap is out of range of a pre-MacII ROM. */
  276.  
  277. Boolean TrapAvailable(short tNumber, TrapType tType)
  278. {
  279.     if ( ( tType == ToolTrap ) &&
  280.         ( gMac.machineType > envMachUnknown ) &&
  281.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  282.         tNumber = tNumber & 0x03FF;
  283.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  284.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  285.     }
  286.     return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, ToolTrap);
  287. } /*TrapAvailable*/
  288.